import java.util.Random;
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class TestFileGenerator {

	private static final Random RANDOM = new Random();
	private static final int MAX_LINE_SIZE_IN_BYTES = 20;

	public static File generateRandomFile(String fileName, File parent,
	        long fileSizeInBytes) throws IOException {
		RandomStringGenerator stringGenerator = new RandomStringGenerator();

		File file = new File(parent, fileName);

		BufferedWriter writer = new BufferedWriter(new FileWriter(file));

		long currentFileSizeInBytes = 0;
		while (currentFileSizeInBytes < fileSizeInBytes) {
			String randomString;

			if (fileSizeInBytes - currentFileSizeInBytes <= MAX_LINE_SIZE_IN_BYTES) {
				randomString = stringGenerator.next(fileSizeInBytes
				        - currentFileSizeInBytes - 1);
			} else {
				long randomLength = (long) (RANDOM.nextDouble()
				        * MAX_LINE_SIZE_IN_BYTES - 1) + 1;
				randomString = stringGenerator.next(randomLength);
			}

			writer.write(randomString);
			writer.newLine();
			currentFileSizeInBytes += randomString.length() + 1;
		}

		writer.flush();
		writer.close();

		return file;
	}
}
